package app.netant.bt.btcat.thread;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

import cn.lily.com.db.DBFactory;
import cn.lily.com.enviroment.Enviroment;

public class BtCatPool {
	
	private List<BtCatThread> threads = new ArrayList<BtCatThread>();
	
	private int maxIdx = 11;
	private int activeIdx = 0;
	private int minIdx = 1;
	
	private int threadCount = 10;

	private String pageUrl = "https://btcat.org/search/%E4%B8%80%E8%88%AC%E3%82%B2%E3%83%BC%E3%83%A0/default-";
	
	public synchronized int getIndex(){
		
		if(activeIdx == 0){
			this.activeIdx = this.minIdx;
			return this.minIdx;
		}
		
		if(this.activeIdx > this.maxIdx){
			return -1;
		}
		
		this.activeIdx ++;
		return this.activeIdx;
	}
	
	public synchronized void remove(BtCatThread thread){
		this.threads.remove(thread);
		System.out.println("当前剩余活动线程数为："+this.threads.size());
	}
	
	public String getPageUrl(){
		return this.pageUrl;
	}
	
	public void start(){
		
		Enviroment.createEnv();
		Enviroment.getEnv().getLogBean().beginLog();
		
		resume();
		
		for(int i=0;i<this.threadCount;i++){			
			BtCatThread thread = new BtCatThread();		
			thread.setParent(this);
			this.threads.add(thread);
		}
		
		int m=1;
		for(Thread thread:this.threads){
			System.out.println("第"+m+"个线程开始启动.........");
			thread.start();
			m++;
		}
		
	}
	
	public static void resume(){
		
		System.out.println("断点续传处理开始........");
		
		DBFactory.getThreadDB().executeUpdate("delete from ${schema}.NET_MARGNET_SRC "
                + "where SRC_URL in "
                + "(select EXCEP_URL from ${schema}.NET_MARGNET_EXCEP)");

		DBFactory.getThreadDB().executeUpdate("delete from ${schema}.NET_MARGNET_SRC "
					                + "where MARGNET_ID not in "
					                + "(select MARGNET_ID from ${schema}.NET_MARGNET_TOL)");
		
		DBFactory.getThreadDB().executeUpdate("delete from ${schema}.NET_MARGNET_TOL "
							        + "where MARGNET_ID not in "
							        + "(select MARGNET_ID from ${schema}.NET_MARGNET_SRC)");
		
		DBFactory.getThreadDB().executeUpdate("delete from ${schema}.NET_MARGNET_EXCEP ");
		
		System.out.println("断点续传处理结束........");
		
	}
	
	public static void main(String[] args) {
		BtCatPool pool = new BtCatPool();
		pool.start();
	}
	
}
